package org.example.system.controller;

import org.example.system.entity.CommentNew;
import org.example.system.service.CommentNewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/commentNew")
public class CommentNewController {
    @Autowired
    private CommentNewService commentNewService;

    @GetMapping
    public List<CommentNew> list() {
        return commentNewService.findAll();
    }

    @PostMapping
    public Map<String, Object> add(@RequestBody CommentNew comment) {
        Map<String, Object> result = new HashMap<>();
        if (comment.getCreateTime() == null) {
            comment.setCreateTime(new java.util.Date());
        }
        int row = commentNewService.add(comment);
        result.put("success", row > 0);
        result.put("message", row > 0 ? "添加成功" : "添加失败");
        return result;
    }

    @PutMapping
    public Map<String, Object> update(@RequestBody CommentNew comment) {
        Map<String, Object> result = new HashMap<>();
        int row = commentNewService.update(comment);
        result.put("success", row > 0);
        result.put("message", row > 0 ? "修改成功" : "修改失败");
        return result;
    }

    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            int row = commentNewService.delete(id);
            result.put("success", row > 0);
            result.put("message", row > 0 ? "删除成功" : "删除失败，id不存在或SQL错误");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "后端异常: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/{id}")
    public CommentNew getById(@PathVariable Long id) {
        return commentNewService.findById(id);
    }
} 